/*
 * Copyright 2019 xiaomaoguai.com All right reserved. This software is the
 * confidential and proprietary information of xiaomaoguai.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with xiaomaoguai.com.
 */

package com.xiaomaoguai.core.next.web.config;

import com.xiaomaoguai.core.next.web.common.HealthController;
import com.xiaomaoguai.core.next.web.common.HomeController;
import com.xiaomaoguai.core.next.web.constants.WebConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Web项目自动配置
 *
 * @author chenyao
 * @since 2018年5月17日 上午11:09:28
 */
@EnableConfigurationProperties(WebProperties.class)
@ComponentScan(basePackages = "com.xiaomaoguai.core.next.web.config")
@Configuration
public class WebAutoConfiguration {
    /**
     * 初始化Web项目自动配置
     */
    public WebAutoConfiguration() {
    }

    /**
     * 创建根目录接口
     *
     * @param applicationName 应用名称
     * @return 根目录接口
     */
    @ConditionalOnProperty(prefix = WebConstants.CONFIG_PREFIX + ".page.home", name = "enabled", matchIfMissing = true)
    @Bean
    public HomeController homeController(@Value("${spring.application.name}") String applicationName) {
        String output = applicationName.replace("-", "_").replace(".", "_");
        String[] words = StringUtils.splitByCharacterTypeCamelCase(output);
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            words[i] = StringUtils.capitalize(word);
        }
        output = StringUtils.join(words).replaceAll("[\\s_]", " ");
        return new HomeController(output + " Service");
    }

    /**
     * 创建健康检查接口
     *
     * @return 健康检查接口
     */
    @ConditionalOnProperty(prefix = WebConstants.CONFIG_PREFIX
            + ".page.health", name = "enabled", matchIfMissing = true)
    @Bean
    public HealthController healthController() {
        return new HealthController();
    }
}
